document.addEventListener('DOMContentLoaded', function() {

    // 更新用户信息显示
    document.getElementById('user-info').textContent = `欢迎回来，${currentUser.name}`;

    // 选项卡切换功能
    const navLinks = document.querySelectorAll('.nav-link');
    const tabContents = document.querySelectorAll('.tab-content');
    const pageTitle = document.getElementById('page-title');

    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const tabId = this.getAttribute('data-tab');

            // 更新活动链接
            navLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');

            // 显示选中的选项卡内容
            tabContents.forEach(tab => tab.classList.remove('active'));
            document.getElementById(tabId).classList.add('active');

            // 更新页面标题
            pageTitle.textContent = this.textContent;

            // 加载对应选项卡的数据
            if (tabId === 'dashboard') loadDashboardData();
            if (tabId === 'user-management') loadUserManagementData();
            if (tabId === 'announcements') loadAnnouncements();
            if (tabId === 'permissions') loadPermissions();
        });
    });

    // 初始化第一个选项卡数据
    loadDashboardData();

    // 数据概览 - 加载统计数据
    function loadDashboardData() {
        // 模拟数据 - 实际项目中应替换为API调用
        const stats = {
            totalUsers: 128,
            companyUsers: 45,
            jobseekerUsers: 83,
            pendingCompanies: 7
        };

        // 更新统计卡片
        document.getElementById('total-users').textContent = stats.totalUsers;
        document.getElementById('company-users').textContent = stats.companyUsers;
        document.getElementById('jobseeker-users').textContent = stats.jobseekerUsers;
        document.getElementById('pending-companies').textContent = stats.pendingCompanies;

        // 渲染图表
        renderStatsChart();
    }

    // 渲染统计图表
    function renderStatsChart() {
        const ctx = document.getElementById('stats-chart').getContext('2d');
        // 销毁已存在的图表
        if (window.statsChart) {
            window.statsChart.destroy();
        }

        // 模拟数据
        const monthlyData = {
            labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
            registrations: [12, 19, 15, 28, 32, 45],
            jobs: [5, 12, 8, 15, 20, 28],
            applications: [18, 35, 25, 42, 58, 72]
        };

        window.statsChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: monthlyData.labels,
                datasets: [
                    {
                        label: '新注册用户',
                        data: monthlyData.registrations,
                        borderColor: '#3498db',
                        backgroundColor: 'rgba(52, 152, 219, 0.1)',
                        tension: 0.3,
                        fill: true
                    },
                    {
                        label: '发布职位',
                        data: monthlyData.jobs,
                        borderColor: '#2ecc71',
                        backgroundColor: 'rgba(46, 204, 113, 0.1)',
                        tension: 0.3,
                        fill: true
                    },
                    {
                        label: '投递简历',
                        data: monthlyData.applications,
                        borderColor: '#e74c3c',
                        backgroundColor: 'rgba(231, 76, 60, 0.1)',
                        tension: 0.3,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top',
                    },
                    title: {
                        display: true,
                        text: '近6个月系统数据趋势'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 用户管理 - 加载用户数据
    function loadUserManagementData() {
        const filter = document.getElementById('user-role-filter');
        const tableBody = document.getElementById('users-table-body');

        // 模拟用户数据
        const users = [
            { id: 1, name: '张三', email: 'zhangsan@example.com', role: 'company', status: 'pending', registered: '2023-10-15' },
            { id: 2, name: '李四', email: 'lisi@example.com', role: 'jobseeker', status: 'active', registered: '2023-10-16' },
            { id: 3, name: '王五', email: 'wangwu@example.com', role: 'company', status: 'active', registered: '2023-10-17' },
            { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: 'admin', status: 'active', registered: '2023-10-10' },
            { id: 5, name: '钱七', email: 'qianqi@example.com', role: 'jobseeker', status: 'banned', registered: '2023-10-12' }
        ];

        // 应用筛选
        const filteredUsers = filter.value === 'all' ? users : users.filter(user => user.role === filter.value);

        // 更新表格内容
        if (filteredUsers.length === 0) {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">没有找到用户数据</td></tr>';
            return;
        }

        tableBody.innerHTML = filteredUsers.map(user => `
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.email}</td>
                <td>${getRoleName(user.role)}</td>
                <td><span class="status-${user.status}">${getStatusName(user.status)}</span></td>
                <td>${user.registered}</td>
                <td>
                    ${user.status === 'pending' ? `<button class="btn btn-success btn-sm" onclick="approveUser(${user.id})")>审核通过</button>` : ''}
                    ${user.status === 'active' ? `<button class="btn btn-danger btn-sm" onclick="banUser(${user.id})")>封禁</button>` : ''}
                    ${user.status === 'banned' ? `<button class="btn btn-warning btn-sm" onclick="unbanUser(${user.id})")>解封</button>` : ''}
                    <button class="btn btn-primary btn-sm" onclick="editUser(${user.id})")>编辑</button>
                </td>
            </tr>
        `).join('');

        // 添加筛选器事件监听
        filter.addEventListener('change', loadUserManagementData);
    }

    // 公告管理 - 加载公告数据
    function loadAnnouncements() {
        const form = document.getElementById('announcement-form');
        const tableBody = document.getElementById('announcements-table-body');

        // 模拟公告数据
        const announcements = [
            { id: 1, title: '系统维护通知', date: '2023-10-20' },
            { id: 2, title: '毕业生招聘季活动开始', date: '2023-10-15' }
        ];

        // 更新公告列表
        tableBody.innerHTML = announcements.map(announcement => `
            <tr>
                <td>${announcement.id}</td>
                <td>${announcement.title}</td>
                <td>${announcement.date}</td>
                <td>
                    <button class="btn btn-primary btn-sm">编辑</button>
                    <button class="btn btn-danger btn-sm">删除</button>
                </td>
            </tr>
        `).join('');

        // 公告发布表单提交处理
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const title = document.getElementById('announcement-title').value;
            const content = document.getElementById('announcement-content').value;

            if (title && content) {
                // 模拟发布公告
                alert('公告发布成功！');
                form.reset();
                loadAnnouncements(); // 重新加载公告列表
            }
        });
    }

    // 权限管理 - 加载权限设置
    function loadPermissions() {
        const roleSelector = document.getElementById('role-selector');
        const permissionsList = document.getElementById('permissions-list');

        // 模拟权限数据
        const permissions = {
            admin: [
                { id: 1, name: '用户管理', enabled: true },
                { id: 2, name: '数据统计', enabled: true },
                { id: 3, name: '公告管理', enabled: true },
                { id: 4, name: '权限管理', enabled: true },
                { id: 5, name: '系统设置', enabled: true }
            ],
            company: [
                { id: 1, name: '发布职位', enabled: true },
                { id: 2, name: '查看简历', enabled: true },
                { id: 3, name: '回复消息', enabled: true },
                { id: 4, name: '用户管理', enabled: false },
                { id: 5, name: '权限管理', enabled: false }
            ],
            jobseeker: [
                { id: 1, name: '投递简历', enabled: true },
                { id: 2, name: '查看职位', enabled: true },
                { id: 3, name: '接收消息', enabled: true },
                { id: 4, name: '用户管理', enabled: false },
                { id: 5, name: '权限管理', enabled: false }
            ]
        };

        // 渲染权限列表
        function renderPermissions(role) {
            const rolePermissions = permissions[role];
            permissionsList.innerHTML = `
                <table class="permissions-table">
                    <thead>
                        <tr>
                            <th>权限名称</th>
                            <th>启用状态</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${rolePermissions.map(perm => `
                            <tr>
                                <td>${perm.name}</td>
                                <td>
                                    <input type="checkbox" ${perm.enabled ? 'checked' : ''} disabled>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
                <button class="btn btn-primary" style="margin-top: 15px;">保存权限设置</button>
            `;
        }

        // 初始渲染
        renderPermissions(roleSelector.value);

        // 角色选择变化时重新渲染
        roleSelector.addEventListener('change', function() {
            renderPermissions(this.value);
        });
    }

    // 辅助函数 - 获取角色显示名称
    function getRoleName(role) {
        const roleNames = { 'admin': '管理员', 'company': '企业用户', 'jobseeker': '求职者' };
        return roleNames[role] || role;
    }

    // 辅助函数 - 获取状态显示名称
    function getStatusName(status) {
        const statusNames = { 'pending': '待审核', 'active': '正常', 'banned': '已封禁' };
        return statusNames[status] || status;
    }

    // 全局函数 - 用户管理操作
    window.approveUser = function(id) {
        if (confirm('确定要审核通过此用户吗？')) {
            alert(`用户 ${id} 审核通过`);
            loadUserManagementData();
        }
    };

    window.banUser = function(id) {
        if (confirm('确定要封禁此用户吗？')) {
            alert(`用户 ${id} 已封禁`);
            loadUserManagementData();
        }
    };

    window.unbanUser = function(id) {
        if (confirm('确定要解封此用户吗？')) {
            alert(`用户 ${id} 已解封`);
            loadUserManagementData();
        }
    };

    window.editUser = function(id) {
        alert(`编辑用户 ${id} - 实际项目中应打开编辑模态框`);
    };

    // 退出登录功能
    window.logout = function() {
        if (confirm('确定要退出登录吗？')) {
            logoutUser();
            window.location.href = 'admin-login.html';
        }
    };
});